package cn.nawang.ebeim.api.repository.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.nawang.ebeim.api.comm.BaseQuery;
import cn.nawang.ebeim.api.domain.Ca;
import cn.nawang.ebeim.api.domain.Department;
import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.vo.UserView;

/**
 * @ClassName: UserQueryImpl
 * @Description: TODO
 * @author 许炜毅
 * @date 2015年8月7日 下午2:16:49
 * @version v1.0
 */
@Repository
public class UserQueryImpl extends BaseQuery {

  private static final String LOAD_USER_BY_MOBILE = "from User u where u.mobile=:mobile";
  private static final String LOAD_USER_BY_MOBILE_NOT_ID =
      "from User u where u.mobile=:mobile and u.id<>:id";
  private static final String LOAD_USER_BY_EMAIL = "from User u where u.email=:email";
  private static final String LOAD_USER_BY_EMAIL_NOT_ID =
      "from User u where u.email=:email and u.id<>:id";
  private static final String LOAD_USER_BY_USERNAME = "from User u where u.username=:username";
  private static final String LOAD_USER_BY_USERNAME_NOT_ID =
      "from User u where u.username=:username and u.id<>:id";
  private static final String LOAD_USER_BY_USERID = "from User u where u.id=:id";
  private static final String LOAD_TERMINAL_BY_TERMINALID = "from Terminal t where t.id=:id";
  private static final String LOAD_DEPARTMENT_DEPARTMENTID = "from Department d where d.id=:id";
  private static final String GET_MAX_RECORED_ID = "select id from User order by selfGrowingId desc";
  private static final String GET_USER =
      "from User u where u.username=:username or u.mobile=:mobile or u.email=:email";
  private static final String GET_USER_NOT_ID =
      "from User u where ( u.username=:username or u.mobile=:mobile or u.email=:email ) and u.id<>:id";
  private static final String UPDATE_USER_DEPT =
      "update User set departmentId=:departId where id in (:id)";
  private static String LOAD_USER_LIST =
      "select " + "new cn.nawang.ebeim.api.vo.UserView(u.id,u.name,u.username,d.name,"
          + "d.id,u.mobile,u.email,u.createTime,u.status,u.customerId,u.role,u.labId,u.labType,"
          + "u.isFirstLogin,u.spaceSize,u.safeLevel,u.bindDevice,u.bindTime,u.bindDeviceName) "
          + "from User u,Department d where u.departmentId=d.id and u.id=:uid";
  private static final String GET_CA = "from Ca c where c.caId=:caId";
  private static final String LOAD_TERMINAL_BY_CAID = "from Terminal t where t.caId=:caId";
  private static final String LOAD_TERMINAL_BY_CAID_DEVICEID_TERMINALID =
      "from Terminal t where t.caId=:caId and t.bindDevice=:deviceId and t.id=:id";
  private static final String LOAD_LICENSE_BY_ID = "from License l where l.id=:id";
  private static final String LOAD_LICENSE_BY_TERMINALID =
      "from License l where l.terminalId=:terminalId";
  private static final String LOAD_TERMINAL_USER =
      "from TerminalUser tu where tu.terminalId=:terminalId and tu.userId=:userId";

  @Autowired
  private EntityManagerFactory entityManagerFactory;

  public long findMaxRecordId() {
    String maxId = getMaxRecordId(GET_MAX_RECORED_ID);
    long mi = Long.valueOf(maxId);
    mi += 1;
    return mi;
  }

  public User findUserByMobile(String mobile) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("mobile", mobile);
      List<User> user = queryObject(LOAD_USER_BY_MOBILE, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByMobileNotId(String mobile, String id) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("mobile", mobile);
      paraMap.put("id", id);
      List<User> user = queryObject(LOAD_USER_BY_MOBILE_NOT_ID, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByEmail(String email) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("email", email);
      List<User> user = queryObject(LOAD_USER_BY_EMAIL, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByEmailNotId(String email, String id) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("email", email);
      paraMap.put("id", id);
      List<User> user = queryObject(LOAD_USER_BY_EMAIL_NOT_ID, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByUsername(String username) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("username", username);
      List<User> user = queryObject(LOAD_USER_BY_USERNAME, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByUsernameNotId(String username, String id) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("username", username);
      paraMap.put("id", id);
      List<User> user = queryObject(LOAD_USER_BY_USERNAME_NOT_ID, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByUsernameOrMobileOrEmail(String username, String mobile, String email) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("username", username);
      paraMap.put("mobile", mobile);
      paraMap.put("email", email);
      List<User> user = queryObject(GET_USER, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByUsernameOrMobileOrEmailNotId(String username, String mobile, String email,
      String id) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("username", username);
      paraMap.put("mobile", mobile);
      paraMap.put("email", email);
      paraMap.put("id", id);
      List<User> user = queryObject(GET_USER_NOT_ID, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public boolean updateUserDept(int departId, String userIdStr) {
    Map<String, Object> paraMap = new HashMap<String, Object>();
    paraMap.put("departId", departId);
    List<String> list = new ArrayList<String>();
    String[] uid = userIdStr.split(",");
    for (int i = 0; i < uid.length; i++) {
      list.add(uid[i]);
    }
    paraMap.put("id", list);
    return execHQL(UPDATE_USER_DEPT, paraMap);
  }

  public UserView findUserById(String userId) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("uid", userId);
      List<UserView> uv = queryObject(LOAD_USER_LIST, paraMap);
      if (uv != null && !uv.isEmpty()) {
        return uv.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public User findUserByUserid(String userid) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("id", userid);
      List<User> user = queryObject(LOAD_USER_BY_USERID, paraMap);
      if (user != null && !user.isEmpty()) {
        return user.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public Department findDepartmentByID(int departmentid) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("id", departmentid);
      List<Department> department = queryObject(LOAD_DEPARTMENT_DEPARTMENTID, paraMap);
      if (department != null && !department.isEmpty()) {
        return department.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public Ca findCaBycaID(String caID) {
    try {
      Map<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("caId", caID);
      List<Ca> ca = queryObject(GET_CA, paraMap);
      if (ca != null && !ca.isEmpty()) {
        return ca.get(0);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public List<Map> findLic(Map<String, Object> map) {
    try {
      String sql = "select 1 from tb_license l,tb_terminal t where l.terminal_id = t.id and l.id='"
          + map.get("id") + "' and t.id='" + map.get("terminal_id") + "' and l.pwd = '"
          + map.get("password") + "' and t.bind_device = '" + map.get("deviceID") + "'";
      List objList = null;
      EntityManager em = entityManagerFactory.createEntityManager();
      try {
        Query query = em.createNativeQuery(sql);
        objList = query.getResultList();
      } catch (Exception ex) {
        ex.printStackTrace();
      }finally{
        em.close();
      }
      return objList;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;

  }

  public List<User> findByDepartmentId(int departmentId) {
    String hql = "from User u where u.departmentId=:departmentId";
    Map<String, Object> paraMap = new HashMap<String, Object>();
    paraMap.put("departmentId", departmentId);
    List<User> users = queryObject(hql, paraMap);
    return users;
  }
  
  public User findByCustomerIdAndAdmin(String customerId){
    String hql="from User u where u.customerId=:customerId and u.role in ('ADMIN','SYSADMIN')";
    Map<String, Object> paraMap = new HashMap<String, Object>();
    paraMap.put("customerId", customerId);
    List<User> users=queryObject(hql, paraMap);
    if(users!=null&&!users.isEmpty()){
      return users.get(0);
    }
    return null;
  }
}
